package com.example.dqdq.lzyim_asm_tvapp.receiver;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.example.dqdq.lzyim_asm_tvapp.MainActivity;
import com.example.dqdq.lzyim_asm_tvapp.R;
import com.example.dqdq.lzyim_asm_tvapp.StartServerActivity;
import com.example.dqdq.lzyim_asm_tvapp.VedioActivity;
import com.example.dqdq.lzyim_asm_tvapp.api.API;
import com.example.dqdq.lzyim_asm_tvapp.utils.AutoScrollTextView;

import org.json.JSONException;

import java.io.IOException;
import java.net.URL;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by DQDQ on 2016/10/15.
 */

public class AdTextReceiver extends BroadcastReceiver {

    private WindowManager wm;
    private View textview;
    private Integer textrecLen = 60;
    private Timer textTimer;
    private Context mContext;
    private Integer nunmber=0;
    private String content="";
    private String imgpath="";
    @Override
    public void onReceive(Context context, Intent intent) {
          nunmber=intent.getIntExtra("number",0);
          content=intent.getStringExtra("content");
          imgpath=intent.getStringExtra("imgpath");
          mContext=context;
        System.out.println("test data:"+String.valueOf(nunmber)+" | "+imgpath);
        wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

//        try {
//            show(context,content,imgpath);
//            showText(context,content);
            textTimer = new Timer();//定时自动关闭字幕
            textrecLen = 60;
            textTimer.schedule(textTimerTask, 1000, 1000);
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }

        if (nunmber!=0)
        {
            nunmber--;
            try {
                 show(context,content,imgpath);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }


    private void show(Context context, String msg,String imgpath) throws JSONException {
        //测试用的废弃方案
//        TextView msgTxv;
        LayoutInflater inflater = LayoutInflater.from(context);

        textview = inflater.inflate(R.layout.bottom, null);
//        msgTxv= (TextView) subtitleView.findViewById(R.id.MsgTxv);
//        msgTxv.setText(array.getJSONObject(0).getString("news"));
//        Download
        //  popView.setOnTouchListener(this);
        if (!imgpath.equals(""))
            new DownloadImageTask().execute(API.SERVERC_URL+imgpath) ;


        TextView editText1 = (TextView) textview.findViewById(R.id.sptxm);
        editText1.setText(msg);


    }

    private class DownloadImageTask extends AsyncTask<String, Void, Drawable>
    {

        protected Drawable doInBackground(String... urls) {
            return loadImageFromNetwork(urls[0]);
        }

        protected void onPostExecute(Drawable result) {
//                mImageView.setImageDrawable(result);

            if (result!=null)
            {
                TextView editText1 = (TextView) textview.findViewById(R.id.sptxm);
                result.setBounds(0, 0, result.getIntrinsicWidth() / 4, result.getIntrinsicHeight() / 4);
                editText1.setCompoundDrawables(result, null, null, null);
                WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
                //窗口类型同系统弹出框

                lp.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
                //响应输入法
                //lp.flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
                //透明层

                lp.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                        | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
                lp.format = PixelFormat.TRANSPARENT;
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                lp.height = WindowManager.LayoutParams.MATCH_PARENT;
                lp.gravity = Gravity.CENTER_VERTICAL;
//                wm.removeView(textview);
                wm.addView(textview, lp);
            }

        }
    }

    /**
     * 定时关闭字幕
     */
    TimerTask textTimerTask = new TimerTask() {
        @Override
        public void run() {
            Log.e("Test cont",String.valueOf(textrecLen));
            if (textrecLen != 0) {
                textrecLen--;
            } else if (textview != null) {
                wm.removeViewImmediate(textview);
                Log.e("test","remove view");
                textTimer.cancel();
              }

            if (textrecLen==0)
            {
                Intent intent1=new Intent(mContext, StartServerActivity.class);
                intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                intent1.putExtra("number",nunmber);
                intent1.putExtra("content",content);
                intent1.putExtra("imgpath",imgpath);
                mContext.startActivity(intent1);
                textTimer.cancel();
                     wm=null;
                    textview=null;
                    textrecLen=null;
                    textTimer=null;
                    mContext=null;
                    nunmber=null;
                    content=null;
                    imgpath=null;
            }
        }
    };

    private Drawable loadImageFromNetwork(String imageUrl)
    {
        Drawable drawable = null;
        try {
            // 可以在这里通过文件名来判断，是否本地有此图片
            drawable = Drawable.createFromStream(
                    new URL(imageUrl).openStream(), "image.jpg");
        } catch (IOException e) {
            Log.d("test", e.getMessage());
        }
        if (drawable == null) {
            Log.d("test", "null drawable");
        } else {
            Log.d("test", "not null drawable");
        }

        return drawable ;
    }



}
